//
//  NetPost02ViewController.m
//  NetPost02
//
//  Created by smu on 11-7-26.
//  Copyright 2011年 duk. All rights reserved.
//

#import "NetPost02ViewController.h"

@implementation NetPost02ViewController
@synthesize postButton;
@synthesize labelMessage;

- (void)dealloc
{
    [postButton release];
    [labelMessage release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}

/*
 
 概述在最初的 http 协议中，没有上传文件方面的功能。 rfc1867 (http://www.ietf.org/rfc/rfc1867.txt) 为 http 协议添加了这个功能。
 客户端的浏览器，如 Microsoft IE, Mozila, Opera 等，按照此规范将用户指定的文件发送到服务器。
 服务器端的网页程序，如 php, asp, jsp 等，可以按照此规范，解析出用户发送来的文件。
 Microsoft IE, Mozila, Opera 已经支持此协议，在网页中使用一个特殊的 form 就可以发送文件。
 绝大部分 http server ，包括 tomcat ，已经支持此协议，可接受发送来的文件。各种网页程序，如 php, asp, jsp 中，对于上传文件已经做了很好的封装。
 
 multipart/form-data 是新增的编码类型，以提高二进制文件的传输效率。
 Content-Length: 424 这里的424是红色内容的总长度（包括最后的回车）
 boundary :分格符
 
 Content-Type: multipart/form-data; boundary=---------------------------7d33a816d302b6
 
 根据 rfc1867, multipart/form-data是必须的.---------------------------7d33a816d302b6 是分隔符，分隔多个文件、表单项。
 
 其中33a816d302b6 是即时生成的一个数字，用以确保整个分隔符不会在文件或表单项的内容中出现。前面的 ---------------------------7d 是 IE 特有的标志。
 
 Mozila 为---------------------------71
 
 */
- (IBAction)post:(id)sender
{
    //文件
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSData *data = [NSData dataWithContentsOfFile:@"/Users/linsmu/Library/Application Support/iPhone Simulator/4.3/Applications/9C4123E2-3A70-40AD-8196-AA5A0C2D7BCD/Documents/favorite/316261683.png"];
    if (!data) {
        NSLog(@"upload no success");
        return;
    }
    if ([data length] == 0) {
        NSLog(@"no data ");
        return;
    }
    
    NSString *  form_fle_input =  @"uploaded";
    NSString *  boundry = @"0xKhTmLbOuNdArY";
//    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//    [request setURL:[[NSURL alloc] initWithString:@"http://192.168.0.101/smu/test/upload/post.php"]];
    
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:
                                   [[NSURL alloc] initWithString:@"http://192.168.0.101/smu/test/upload/post.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundry]
            forHTTPHeaderField:@"Content-Type"];
    NSMutableData *postData = [NSMutableData dataWithCapacity:[data length] + 512];
    [postData appendData:
     [[NSString stringWithFormat:@"--%@\r\n",boundry] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:
     [[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"file.bin\"\r\n\r\n",
       form_fle_input] dataUsingEncoding:NSUTF8StringEncoding]];
    [postData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 
    [postData appendData:data];
    [postData appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundry] 
                           dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postData];
    if (!request) {
        NSLog(@"no success");
        return;
    } 
    NSURLConnection *connection = 
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (!connection) {
        NSLog(@"NO");
    } 
    
    
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}




#pragma mark -
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
        NSLog(@"RSSParser: Response is an NSHTTPURLResponse: Response=%d",[httpResponse statusCode]);
        if ([httpResponse statusCode] >= 400 && [httpResponse statusCode] <= 599) {
            NSLog(@"connection NO");
        } else if([httpResponse statusCode] >= 100 && [httpResponse statusCode] <= 299) {
            NSLog(@"connection YES");
        } else {
            NSLog(@"RSSParser: Status code is unknown.");
        }
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [rssItemData appendData:data];

    NSLog(@"connection YES1");

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSString *dataString = [[[NSString alloc] initWithData:
                             rssItemData encoding:NSUnicodeStringEncoding] autorelease];
    if ([dataString length] > 0) {
        NSLog(@"datadata%@",dataString);
    } 
    NSLog(@"connection YES2");

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"connection YES3");

}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    NSLog(@"connection YES4");
}
@end
